import { CONTENT_STATUS_KEYS, CreateArticleDto, UpdateArticleDto } from '@ai/entity';
import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager';
import { Body, Controller, Delete, Get, Inject, Param, Patch, Post, Query } from '@nestjs/common';
import { Public } from '@/utils/metadata/public';
import { ArticleCategoryService } from '../article-category/article-category.service';
import { ARTICLE_CATEGORY_CACHE_KEY_MAP } from '../article-category/config';
import { ArticleService } from './article.service';

@Public()
@Controller('article')
export class ArticleController {
    constructor(
        @Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
        private readonly articleService: ArticleService,
        private readonly articleCategoryService: ArticleCategoryService
    ) {}

    @Post()
    create(@Body() createArticleDto: CreateArticleDto) {
        this.cacheManager.del(ARTICLE_CATEGORY_CACHE_KEY_MAP.FIND_LIST_BY_ARTICLES);
        return this.articleService.create(createArticleDto);
    }

    @Get()
    findEnableArticle(@Query('status') status: CONTENT_STATUS_KEYS) {
        return this.articleService.findAll({ status });
    }

    @Get('all')
    findAll() {
        return this.articleService.findAll();
    }

    @Get('query')
    async query(@Query('category') category: string) {
        const categoryInfo = await this.articleCategoryService.findOne({ value: category });
        if (!categoryInfo) return [];
        return this.articleService.findAll({ category: categoryInfo._id.toString() });
    }

    @Get(':id')
    findOne(@Param('id') id: string) {
        return this.articleService.findById(id);
    }

    @Patch(':id')
    update(@Param('id') id: string, @Body() updateArticleDto: UpdateArticleDto) {
        this.cacheManager.del(ARTICLE_CATEGORY_CACHE_KEY_MAP.FIND_LIST_BY_ARTICLES);
        return this.articleService.update(id, updateArticleDto);
    }

    @Patch('/like/:id')
    async like(@Param('id') id: string) {
        const { like = 0 } = await this.articleService.findById(id);
        return this.articleService.update(id, { like: like + 1 });
    }

    @Patch('/dislike/:id')
    async dislike(@Param('id') id: string) {
        const { dislike = 0 } = await this.articleService.findById(id);
        return this.articleService.update(id, { dislike: dislike + 1 });
    }

    @Delete(':id')
    remove(@Param('id') id: string) {
        this.cacheManager.del(ARTICLE_CATEGORY_CACHE_KEY_MAP.FIND_LIST_BY_ARTICLES);
        return this.articleService.remove(id);
    }
}
